<?php
/**
 * Created by PhpStorm.
 * User: wangjun
 * Date: 2017/2/6 0006
 * Time: 下午 6:35
 */
class VoteModel
{
	private $topicModel;

	function __construct()
	{
		$this->topicModel          	=   new TopicModel();
	}

	/**
	 * 添加投票信息
	 * @param unknown $info
	 * @return boolean|Ambigous <multitype:, boolean, unknown>
	 */
	public function addVoteLink($uid, $tid, $vote){
		// 判断info中的vote
		if (empty($uid) || empty($tid) || empty($vote)) {
			return false;
		}

		$params   =   array(
			'tid'         => $tid,                //话题ID
			'uid'         => $uid,                //用户ID
			'type'        => '0',                 //是否多选 1:多 0:单
			'max_options' => count($vote['opts']),//最大选项条目数
			'dateline'    => $vote['dateline'],   //投票截止时间
			'time'        => AC::SERVER_TIME,     //创建时间
			'status'      => '0',                 //状态 0:正常 1:删除2:过期
			'extra'       => ''                   //附件字段
		);

		$voteLinkId = $this->topicModel->addVoteLink($params);
		return $voteLinkId;
	}

	/**
	 * 添加投票选项信息
	 * @param unknown $info
	 * @return boolean|Ambigous <multitype:, boolean, unknown>
	 */
	public function  addVoteOptions($uid, $topicId, $vote, $voteLinkId){
		if (empty($uid) || empty($topicId) || empty($vote) || empty($voteLinkId)) {
			return false;
		}

		$options = array(
			'tid'         => $topicId,
			'vid'         => $voteLinkId,
			'vote_num'    => '0',
			'extra'       => ''
		);

		$result = array();
		foreach ($vote['opts'] as $value){
			$options['content'] = $value;
			$result[] = $this->topicModel->addVoteOptions($options);
		}
		return $result;
	}

	/**
	 * 判断投票(选项数、各选项长度、时间)
	 * @param unknown $info
	 * @return boolean|Ambigous <boolean, multitype:string >
	 */
	public function filterTopicVote($vote){
		if (empty($vote) || empty($vote['opts'])){
			return FALSE;
		}

		// check options
		$options  = array_slice($vote['opts'], 0, 6);
		if (count($options) < 2) {
			AC::$errorNo    =   'GRC001';
			return  FALSE;
		}

		// filter options
		foreach ($options as &$value) {
			$value = UK::getstr($value, 60, '', 1);
		}

		$result = array('opts' => $options, 'dateline' => 0);
		$duration = intval($vote['duration']);

		// dateline
		if ($duration) {
			$oneDay     = 86400; //86400
			$thirtyDays = 2592000; //30 * 86400
			$duration = ($duration <= $oneDay) ? $oneDay : $duration;
			$duration = ($duration >= $thirtyDays) ? $thirtyDays : $duration;
			$result['dateline'] = AC::SERVER_TIME + $duration;
		}

		return $result;
	}

	/**
	 * 获取投票详情
	 * @param unknown $tid
	 * @param unknown $author_uid
	 * @param unknown $vote
	 * @param unknown $host_uid
	 * @return StdClass|Ambigous <StdClass, Ambigous>
	 */
	public function getVoteInfo($tid,$author_uid ,$vote, $host_uid) {
		// 参数过滤
		if (empty($vote)) return (Object) array(); // 返回空对象

		// 1.获取Link表信息
		$link = $this->getVoteLinkInfo($tid, $host_uid);
		if (empty($link)) return (Object) array();

		//2获取Options信息
		$voteOptionsInfo = $this->getVoteOptions($tid,$author_uid, $host_uid);
		if (empty($voteOptionsInfo)) return (Object) array();

		// 返回结果拆分
		$isvoted = $voteOptionsInfo['isvoted'];
		$total_vote_num = $voteOptionsInfo['total_vote_num'];
		$list = $voteOptionsInfo['list'];

		// 3.组装
		$vote =  $this->restructVoteData($link,$list,$isvoted,$total_vote_num);
		return $vote;
	}

	/**
	 * 获取投票表数据
	 * @param unknown $tid
	 * @return multitype:|Ambigous <boolean, multitype:, unknown>
	 */
	public function getVoteLinkInfo($tid) {
		if (empty($tid)) return array();

		$voteLink = $this->topicModel->getVoteLinkInfo($tid);
		if (empty($voteLink)) return array();

		// 判断link信息
		$voteLinkInfo = $this->getVoteExpired($voteLink);
		if (!$voteLinkInfo) {
			return array();
		}

		return $voteLinkInfo;
	}

	/**
	 * 判断是否过期
	 * @param unknown $info
	 * @return unknown|number|boolean
	 */
	public function getVoteExpired($info) {
		if (empty($info) || $info['status'] == 1) return false;

		if($info['status'] == 2 || intval($info['dateline']) < 1){
			return $info;
		}

		if ($info['dateline'] < AC::SERVER_TIME){
			$voteEdit =  $this->updataVoteStatus($info['id'], 2);
			if(empty($voteEdit)) return false;

			$info['status'] =2;
		}

		return $info;
	}

	/**
	 * 修改投票表状态
	 * @param unknown $vid
	 * @param unknown $status
	 * @return boolean
	 */
	public function updataVoteStatus($vid,$status) {
		if(empty($vid)) return false;

		$voteEdit =  $this->topicModel->editVoteLink($vid,$status);
		if(empty($voteEdit)) return false;

		return true;
	}

	/**
	 * 获取选项表数据 查看是否投票
	 * @param unknown $tid
	 * @param unknown $author_uid
	 * @param unknown $uid
	 * @return multitype:|multitype:mixed Ambigous <string, unknown>
	 */
	public function getVoteOptions ($tid,$author_uid, $uid) {
		if (empty($tid)) return array();

		// 默认未投过
		$isVoted = 0;
		// 1.获取option列表
		$voteOptions   = $this->topicModel->getVoteOptionsInfo(array('tid'=> $tid)); //选项表数据
		if(empty($voteOptions)) return array();

		//获取用户投票log
		$log_ids = array();
		if($uid){
			$log_ids = $this->topicModel->getUserVoteLogIds($tid,$author_uid, $uid);
		}
		$isVoted = $total = 0;
		$list = $tmp = array();
		foreach ($voteOptions as $value) {
			$tmp = $this->restructVoteOptionData($value, $log_ids);
			if (empty($tmp['id'])) continue;
			$isVoted += $tmp['isvoted'];
			$total += $tmp['vote_num'];
			$list[] = $tmp;
		}
		return array('isvoted' => $isVoted, 'total_vote_num' => $total, 'list' => $list);
	}

	/**
	 * option数据组装 判断是否投票
	 * @param unknown $option
	 * @param unknown $log_ids
	 * @return multitype:string unknown
	 */
	private function restructVoteOptionData ($option, $log_ids = array()) {
		$res = array(
			"id"=> $option['id'],
			"tid"=> $option['tid'],
			"vote_num"=>$option['vote_num'],
			"content"=>$option['content'],
			"time"=>$option['time'] ,
			"isvoted"=> "0"
		);
		$oid = array('oid' => $res['id']);
		if ($log_ids && in_array($oid, $log_ids)) {
			$res['isvoted'] = '1';
		}
		return $res;
	}

	/**
	 * 组装返回投票结构
	 * @param unknown $link
	 * @param unknown $options
	 * @param unknown $isVoted
	 * @return StdClass|Ambigous <unknown, string>
	 */
	public function restructVoteData($link,$list,$isvoted,$total_vote_num){
		if (empty($link) || empty($list)) return (Object) array();

		$result = array(
			'id'            =>  '0',    //id
			'tid'           =>  '0',    //话题ID或者日记的bodyId
			'max_options'   =>  '0',    //最大选择条数
			'type'          =>  '1',    //单选多选
			'dateline'      =>  '0',    //过期时间
			'status'        =>  '0',    //状态0:正 1:删2:过
			'time'          =>  '0',    //创建时间
			'isvoted'       =>  '0',    //是否投过
			'total_vote_num'=>  '0',     //总票数
			'options'     =>  (Object) array() // 选项
		);

		// link关系表数据返回
		$result = UK::assembleReplacedFieldData($link, $result, array(
			'id'          =>  'id',
			'tid'         =>  'tid',
			'max_options' =>  'max_options',
			'type'        =>  'type',
			'dateline'    =>  'dateline',
			'status'      =>  'status',
			'time'        =>  'time',
		));
		//总票数
		$result['total_vote_num'] = $total_vote_num;
		// 是否透过
		$result['isvoted'] = $isvoted;
		// option数据
		$result['options'] = array(
			'list'    =>  $list,
			'counts'  =>  count($list)
		);
		return $result;
	}

	/**
	 * 投票数据添加
	 * @param unknown $voteOptionsInfo
	 * @param unknown $host_id
	 * @param unknown $author_uid
	 * @param unknown $oid
	 * @return boolean
	 */

	public  function addTopicVoteLogs($oids_arr, $uid, $author_uid, $tid, $vid){
		if (empty($oids_arr) || empty($uid) || empty($author_uid) || empty($tid) || empty($vid)) {
			return false;
		}

		// $oids_arr 写log
		foreach ($oids_arr as $val) {
			$res1 = $this->topicModel->addVoteLogs($val, $uid, $author_uid, $tid, $vid);
			if ($res1) {
				$result =  $this->increaseOptionVoteNum($val);
			}
		}
		return true;
	}

	public function increaseOptionVoteNum($id) {
		$result = $this->topicModel->increaseOptionVoteNum($id);
		return $result;
	}

}